if(typeof FMP == 'undefined') var FMP = {};

String.prototype.pad = function(l, s){
	return (l -= this.length) > 0 
		? (s = new Array(Math.ceil(l / s.length) + 1).join(s)).substr(0, s.length) + this + s.substr(0, l - s.length) 
		: this;
};

FMP.browser = (typeof chrome == 'undefined' ? 'firefox' : 'chrome');
FMP.serverHost = 'http://home.codeone.pl/player_symfony/web';
FMP.status = {};

FMP.mainStatus = {
	status: null,
	pass: null,
	
	ok: function() {
		FMP.mainStatus.set(true);
		FMP.tab.close('login');
	},
	
	get: function() {
		return this.status;
	},
	
	set: function(stat) {
		if(!stat) {
			this.status = null;
			return;
		}
		
		if(!FMP.data.playerLoaded)
		{
			setTimeout(function() { FMP.mainStatus.set(stat); }, 500);
			return;
		}
		
		FMP.postToFrame({action: "options", "data": FMP.data.options.get()});
		
		if(FMP.mainStatus.pass) {
			FMP.playingNow.add(FMP.mainStatus.pass);
			delete FMP.mainStatus.pass;
		}
		
		this.status = stat;
	}
};


FMP.playingNow = {
	list: [],
	lastIndex: null,
	
	lastId: 0,
	
	reset: function() {
		this.list = [];
		this.lastId = 0;
	},
	
	add: function(data) {
		var force = false, replace = false;
		if(data.replace)
			this.list = [];
		
		if(data.force)
			force = true;
		
		var result = {action: "playNow", force: force};
		
		if(data.position && data.position == 'start') {
			result.moveIndex = data.list.length;
			this.list = data.list.concat(this.list);
		} else {
			this.list = this.list.concat(data.list);
		}
		
		for(var i=0;i<this.list.length;i++) {
			if(!this.list[i].unique_id) {
				this.lastId++;
				this.list[i].unique_id = this.lastId;				
			}
		}
		
		if(typeof data.newIndex != 'undefined') {
			result['index'] = data.newIndex;
		}
		
		result['list'] = this.list;
		
		FMP.database.updateOption('lastPlaying', this.list);
		
		FMP.postToFrame(result);
	},
};

FMP.copyToClipboard = function(msg)
{
	FMP.jQuery('body').append('<textarea id="ta"></textarea>');
	var ta = document.getElementById('ta');
	ta.value = msg;
	ta.select();
	document.execCommand("copy", false, null);
	FMP.jQuery('#ta').remove();
};

FMP.getVideoUrl = function(src, id) {
	var url;
	
	if(src == 'y') 
		url = 'http://www.youtube.com/watch?v='+id;
	else
		url = "http://vimeo.com/"+id;
	
	return url
};

FMP.logout = function() {
	var token = FMP.data.token;
	
	if(!token)
		return;
	
	FMP.jQuery.ajax({
		url: FMP.serverHost+"/logout",
		type: 'POST',
		data: {token: token},
		dataType: 'json'
	});
};

FMP.loadNewUser = function(userID, username, token) {
	FMP.tab.close('library');
	FMP.playingNow.reset();
	
	FMP.data.token = token;
	FMP.data.userID = userID;
	FMP.data.username = username;
	FMP.mainStatus.set(null);
	
	if(FMP.data.playerLoaded) {
		FMP.postToFrame({action: "reset"});
	}
	
	setTimeout(function() { FMP.database.loadData(); }, 1);
};

FMP.checkSession = function() {
	var token;
	var $ = FMP.jQuery;
	
	try {
      token = localStorage.getItem('token');
    }catch(e) {}
	
	var userID = null, username = null;
	
	if(!token) {
		FMP.loadNewUser(userID, username, null);
		return;
	}
	
	$.ajax({
		url: FMP.serverHost+"/check",
		type: 'POST',
		data: {token: token},
		dataType: 'json',
		success: function(d) {
			if(d.userID) {
				username = d.username;
				userID = d.userID;
			} else {
				localStorage.removeItem('token');
			}
			FMP.loadNewUser(userID, username, token);
			
		}, error: function() {
			FMP.loadNewUser(null, null, null);
		}
	});
};

FMP.popup = {
	items: {},
	
	show: function(text) {
		
		for(var i in this.items) {
			this.items[i].cancel();
		}
		
		var id = Math.random();
		
		this.items[id] = webkitNotifications.createNotification('', "New song", text);
		this.items[id].show();
		
		setTimeout(function() { 
			if(FMP.popup.items[id]) {
				FMP.popup.items[id].cancel(); 
			}
		}, 3000);
	}
};

FMP.data = {
	userID: null,
	username: null,
	token: false,
	playerLoaded: false,
	options: {
		data: {
			shuffle: false,
			repeat: false,
			volume: 100,
			showPlaylistInPlayer: true,
			lastVolume: 100,
			showPopupOnNewSong: true,
			loadLastPlaylistOnStart: true,
			playLastPlaylistOnStart: true
		},
		set: function(k, v, skipSave) {
			if(this.data['volume'] == null)
				this.data['volume'] = 100;
			
			if(this.data[k] == undefined || this.data[k] == null)
				return;
			
			this.data[k] = v;
			
			if(!skipSave) {
				FMP.database.updateOption(k, v);			
				FMP.postToFrame({action: "options", "data": this.data});
			}
		},
		
		get: function(k) {
			if(k == undefined)
				return this.data;
			
			if(this.data[k] == undefined || this.data[k] == null)
				return;
			
			return this.data[k];
		},
		populate: function(r) {
			var list = [];
			var idx = null;
			
			for(var i=0;i<r.result.length;i++) {
				var opt = r.result[i].meta_key;
				var val = JSON.parse(r.result[i].meta_value);
				
				this.set(opt, val, true);
				
				if(opt == 'lastPlaying') {
					list = val;
				}
				if(opt == 'lastIndex') {
					idx = val;
				}
			}
			
			if(FMP.data.options.get('loadLastPlaylistOnStart')) {
			
				var force = false;
				if(FMP.data.options.get('playLastPlaylistOnStart')) {
					force = true;
				}
				FMP.mainStatus.pass = {force: force, list: list, newIndex: idx, replace: true};
			}
		}
	},
	
	channels: [],
	genres: [],
	playlists: [],
	years: [],
	albums: [],
	
	add: function(type, obj) {
		this[type].push(obj);
		this.sort(type);
		return this[type].indexOf(obj);
	},
	
	update: function(type, id, name) {
		for(var i=0; i< this[type].length; i++) {
			var v = this[type][i];
			if(v.id == id) {
				this[type][i] = FMP.jQuery.extend(true, {}, this[type][i], {name: name});
				break;
			}
		}
	},
	
	sort: function(type) {
		this[type].sort(function(a,b) {
			var a1 = FMP.jQuery.trim(a.name).toLowerCase();
			var b1 = FMP.jQuery.trim(b.name).toLowerCase();
			
			if(a.id == -1) {
				return 1;
			}
			if(b.id == -1) {
				return -1;
			}
			
			if(a1 < b1)
				return -1;
			return 1;
		});
	},
	
	getSorted: function(type) {
		this.sort(type);
		
		var arr = [], fld;
		if(type == 'genres')
			fld = 'data-genre-id';
		else if(type == 'playlists')
			fld = 'data-playlist-id';
		else if(type == 'years')
			fld = 'data-year';
		else if(type == 'albums')
			fld = 'data-album';
		else if(type == 'channels')
			fld = 'data-channel';
			
		for(var i = 0; i < this[type].length; i++) {
			if(type == 'genres' || type == 'playlists' || type == 'channels') {
				var attr = {"class": "treeEditContextMenu"};
				attr[fld] = this[type][i].id;
			} else {
				var attr = {};
				if(type == 'years' || type == 'albums') {
					attr["class"] = "treeItemPlayContext";
				}
				attr[fld] = this[type][i].id.toString();
			}
			
			var name = this[type][i].name.toString();
			attr.title = name;
			
			arr.push({data: name, attr: attr});
		}
		return arr;
	},
	
	populate: function(type, a) {
		FMP.data[type] = [];
		
		for(var i=0;i<a.result.length;i++) 
		{
			FMP.data[type].push(a.result[i]);
		}
		
		if(type == 'genres') {
			FMP.data[type].push({"id": -1, name: "Not classified"});
		} else if(type == 'years' || type == 'albums') {
			FMP.data[type].push({"id": -1, name: "Not set"});
		}
	},
	
	
	addSong: function(type, id, song_list, top) {
		
		var queries = [], table, field;
		
		if(type == 'genres') {
			table = 'genres_songs';
			field = 'genre_id';
		} else if(type == 'playlists') {
			table = 'playlists_songs';
			field = 'playlist_id';
			
			
			if(top)
			{
				queries.push(
					{query: FMP.squel.update().table('playlists_songs').set('position', 'position + '+(song_list.length), true).where('playlist_id', id).where('position', '>=', 1) }
				);
			}
		}
		
		for(var i=0; i<song_list.length ; i++) {
			var song_id = song_list[i];
			
			var qry = FMP.squel.insert().into(table).set(field, id).set('song_id', song_id);
			
			if(type == 'playlists')
				if(top)
					qry.set('position', i+1);
				else
					qry.set('position', "COALESCE( (SELECT MAX(position) FROM playlists_songs where playlist_id = "+id+")+1, 1 )", true);
			
			queries.push({query: qry});
		}
		
		FMP.database.query(queries, FMP.refreshVisibleTree);
	},	
	
	deleteSong: function(type, id, song_list) {
		var queries = [], table, field;
		
		if(type == 'genres') {
			table = 'genres_songs';
			field = 'genre_id';
		} else if(type == 'playlists') {
			table = 'playlists_songs';
			field = 'playlist_id';
		}
	
		for(var i=0; i<song_list.length ; i++) {
			var song_id = song_list[i];
			queries.push({query: FMP.squel.delete().from(table).where(field, id).where('song_id', song_id)});
		}
		
		FMP.database.query(queries, FMP.refreshVisibleTree);
	},
};

FMP.secondsToLength = function(d) {
	d = Number(d);
	
	var mins = Math.floor(d/60);
	var secs = d % 60;
	
	return mins.toFixed().pad(2, "0")+':'+secs.toFixed().pad(2, "0");
};

FMP.lengthToSeconds = function(str) {
	if(!str) return 0;
	
	var p = str.split(':'),
		s = 0, m = 1;

	while (p.length > 0) {
		s += m * parseInt(p.pop());
		m *= 60;
	}
	return s;
};

FMP.postToFrame = function(data) {
	try {
		FMP.jQuery('#ifr').get(0).contentWindow.postMessage(data, "*");
	}
	catch(e) {
		FMP.error(e);
	}
};

FMP.startup = function(error) {
	var ifr = FMP.jQuery('#ifr');
	var token = Math.random();
	
	if(error) {
		ifr.attr('src', 'about:blank').data('token', '');
	}
	
	var url = "http://home.codeone.pl/player/test.html"; //?t="+Math.random();

	ifr.data('token', token).data('timeout', setTimeout(function () { FMP.startup(true); }, 3000));
	
	ifr.attr('src', url).bind('load', function(e) {
		var that = FMP.jQuery(this);
		clearTimeout(that.data('timeout'));
		that.unbind('load').data('timeout', setTimeout(function() { FMP.startup(true); }, 10000));
		FMP.postToFrame({action: "ping", "token": that.data('token')});
	});
};


FMP.tab = {
	pages: {
		library: 	{url: chrome.extension.getURL("library.html")},
		login:   	{url: chrome.extension.getURL("login.html")},
		register: 	{url: FMP.serverHost+'/register' }
	},
	
	close: function(page) {
		if(!this.pages[page])
			return;
		
		var url = this.pages[page].url;
		
		chrome.windows.getAll({populate: true}, function(windows) {
			for(var i=0;i<windows.length;i++) {
				var wnd = windows[i];
				if(wnd.type != 'normal')
					continue;
				
				for(var j in wnd.tabs) {
					var tab = wnd.tabs[j];
					if(tab.url.indexOf(url) == 0 || tab.url.indexOf(url.replace('http://', 'https://')) == 0) {
						chrome.tabs.remove(tab.id);
					}
				}
			}
		});
	},
	
	send: function(page, msg, data) {
		if(!this.pages[page])
			return;
		
		var url = this.pages[page].url;
		
		var views = chrome.extension.getViews();
		
		for (var i = 0; i < views.length; i++)
		{
			var view = views[i];
			//If this view has the right URL and hasn't been used yet...
			if(view.location.href.indexOf(url) == 0 || view.location.href.indexOf(url.replace('http://', 'https://')) == 0) {
				if(view[msg])
					view[msg](data);
				
				break;
			}
		}
	},
	
	open: function(page) {
	
		if(!this.pages[page])
			return;
		
		var url = this.pages[page].url;
	
		chrome.windows.getAll({populate: true}, function(windows) {
			for(var i=0;i<windows.length;i++) {
				var wnd = windows[i];
				if(wnd.type != 'normal')
					continue;
				
				for(var j in wnd.tabs) {
					var tab = wnd.tabs[j];
					if(tab.url.indexOf(url) == 0 || tab.url.indexOf(url.replace('http://', 'https://')) == 0) {
						chrome.windows.update(wnd.id, {focused: true}, function(wnd) {
							chrome.tabs.update(tab.id, {active: true});
						});
						return;
					}
				}
			}
			
			chrome.tabs.getSelected(null, function(tab) {
				chrome.tabs.create({
					url: url,
					index: tab.index + 1
				});
			});
		});
	}
};

FMP.preStartup = function(event) {
	/*
	var request = new XMLHttpRequest();  
	request.open('GET', 'js/jquery-1.7.1.min.js', false);   
	request.send(null);
	try {
		eval(request.responseText);
	} catch(e) {
		FMP.error(e);
	}
	
	var request = new XMLHttpRequest();  
	request.open('GET', 'js/database.js', false);   
	request.send(null);
	try {
		eval(request.responseText);
	} catch(e) {
		FMP.error(e);
	}
	
	var request = new XMLHttpRequest();  
	request.open('GET', 'js/squel.js', false);   
	request.send(null);
	try {
		eval(request.responseText);
	} catch(e) {
		FMP.error(e);
	}
	*/

	FMP.squel = squel;
	
	var jQuery = window.jQuery.noConflict(true);
	if( typeof(jQuery.fn._init) == 'undefined') { jQuery.fn._init = jQuery.fn.init; }
	FMP.jQuery = jQuery;
	
	FMP.jQuery.ajaxSetup({
		timeout: 120000,
		method: 'GET',
		dataType: 'text'
	});
	
	FMP.jQuery(document).ajaxError(function(e, xhr, opt) {
		FMP.error({message: 'Error ' + xhr.status + ' while downloading ' + opt.url});
	});
	
	FMP.startup();
	
	FMP.log('FMP loaded successfully');
	
	FMP.database.open(FMP.checkSession);
};

FMP.time = function() {
	var d = new Date();
	var h = d.getHours()+"";
	var m = d.getMinutes()+"";
	var s = d.getSeconds()+"";
	if (h.length == 1) h = "0" + h;
	if (m.length == 1) m = "0" + m;
	if (s.length == 1) s = "0" + s;

	return h+':'+m+':'+s;
};

FMP.log = function() {
	var time = '['+FMP.time()+']';
	
	var args = [];
	args.push(time);
	
	for( var i = 0; i < arguments.length; i++ )
		args.push(arguments[i]);
	
	console.log.apply(console, args);
};

FMP.error = function() {
	var time = '['+FMP.time()+']';
	
	var args = [];
	args.push(time);
	
	for( var i = 0; i < arguments.length; i++ )
		args.push(arguments[i].message);
		
	console.error.apply(console, args);
};

window.addEventListener("load", function(e) { setTimeout(function() { FMP.preStartup(e); }, 250); }, false);